﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace SocketClientMelo
{
    public partial class FormClientAppForm : Form
    {
       private NetworkStream networkStream;
        private BinaryWriter binaryWriter;
        private BinaryReader binaryReader;
        private TcpClient tcpClient;

        private Thread thread;

        public FormClientAppForm()
        {
            InitializeComponent();
            thread = new Thread(new ThreadStart(RunClient));
            thread.Start();
        }

        public void RunClient()
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect("127.0.0.1", 2001);

                networkStream = tcpClient.GetStream();
                binaryWriter = new BinaryWriter(networkStream);
                binaryReader = new BinaryReader(networkStream);

                String message = "";
                do
                {
                    try
                    {
                        message = binaryReader.ReadString();
                        MessageBox.Show(message, "Mensagem Recebida do servidor");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Erro");
                        message = "FIM";
                    }
                } while (message != "FIM");

                binaryWriter.Close();
                binaryReader.Close();
                networkStream.Close();
                tcpClient.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
             try
            {
                binaryWriter.Write(textBoxMensagem.Text);
            }
            catch (SocketException socketEx)
            {
                MessageBox.Show(socketEx.Message, "Erro");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            tcpClient.Close();
        }
    }
}
